package com.zipking.cloud.springbootmybatis.util;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ProductAggregator {

    private final SupplierService supplierA;
    private final SupplierService supplierB;
    private final SupplierService supplierC;

    public ProductAggregator(SupplierService supplierA, SupplierService supplierB, SupplierService supplierC) {
        this.supplierA = supplierA;
        this.supplierB = supplierB;
        this.supplierC = supplierC;
    }

    public void aggregateProductDetails(String productId) {
        // 使用 CompletableFuture.allOf 来等待所有供应商返回结果
        CompletableFuture.allOf(
                supplierA.getProductDetails(productId),
                supplierB.getProductDetails(productId),
                supplierC.getProductDetails(productId)
        ).thenRun(() -> {
            System.out.println("All suppliers have responded.");
            displayProductDetails(supplierA.getProductDetails(productId), supplierB.getProductDetails(productId), supplierC.getProductDetails(productId));
        });
    }

    private void displayProductDetails(CompletableFuture<Product> futureA, CompletableFuture<Product> futureB, CompletableFuture<Product> futureC) {
        try {
            Product productA = futureA.get();
            Product productB = futureB.get();
            Product productC = futureC.get();

            System.out.println("Product A: " + productA);
            System.out.println("Product B: " + productB);
            System.out.println("Product C: " + productC);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SupplierService supplierA = new SupplierA();
        SupplierService supplierB = new SupplierB();
        SupplierService supplierC = new SupplierC();

        ProductAggregator aggregator = new ProductAggregator(supplierA, supplierB, supplierC);
        aggregator.aggregateProductDetails("12345");

    }
}
